/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.policy;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import sagroup.dracots.DracoTS;
import sagroup.dracots.ShareTuple;

import lime2.LimeServerID;
import lime2.Location;
import lime2.ReconciliationJob;

/**
 * @author Xing Jiankuan
 *
 */
public class RPReconciliation implements ReconciliationJob {

	//HashMap[LimeServerID, HashSet[tsName]]
	static HashMap existsHosts = new HashMap();
	
	private Logger LOG = Logger.getLogger(this.getClass().getName());
	
	/* (non-Javadoc)
	 * @see lime2.ReconciliationJob#doReconciliation(java.lang.String, lime2.LimeServerID)
	 */
	public void doReconciliation(String tsName, LimeServerID host) {}
	
	/**
	 * Replicate the replication policy's replication policy and 
	 * push it to the target
	 * @param tsName
	 * @param host
	 * @author Xing Jiankuan
	 */
	private void replicateAndPush(String tsName, LimeServerID host) {
		
		DracoTS dts = DracoTS.get(tsName);
		RPTuple rpt = (RPTuple)dts.rdp(RPTuple.RP2_LOCAL_TEMPLATE);
		//replicate it and push it
		Location target = new Location(host);
		RPTuple newrpt = (RPTuple) rpt.replicate(target);
		dts.pushReplica(new ShareTuple[]{newrpt}, target);
	}

	public void postReconciliaton(String tsName, LimeServerID host) {
		//find whether this reconciliation was done before
		Set tsNames = (Set)existsHosts.get(host);
		if(tsNames != null) {
			if(tsNames.contains(tsName)) {
				//this job is done, just exit
				return;
			} else {
				//the host is engaged, but the tuple space is new to 
				//reconciliation
				replicateAndPush(tsName, host);
				tsNames.add(tsName);
			}
		} else {
			replicateAndPush(tsName,host);
			tsNames = new HashSet();
			tsNames.add(tsName);
			existsHosts.put(host, tsNames);
		}
		LOG.info(tsName + "@" + Location.HERE.getID() + " sends RP2 to " + host);
	}
}
